package com.nervenets.web.controller.handler.user.user;

import com.nervenets.utils.StringUtils;
import com.nervenets.web.controller.Global;
import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.controller.handler.user.UserModel;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.User;
import com.nervenets.web.redis.domain.user.UserStored;

import javax.servlet.http.HttpServletRequest;

public class UserRegisterHandler extends Handler<UserRegisterParams> {
    @Override
    public String handle(UserRegisterParams params, HttpServletRequest request) throws Exception {
        return (String) redisSyncLocker.keyLock(params.getMobile(), o -> {
            if (!params.getVCode().equals(globalService.getGlobalPair(String.format(Global.Constants.MOBILE_VALIDATION_CODE, params.getMobile())))) {
                return errorMessage(MessageCode.code_444, "您填写的验证码不正确或失效！");
            }

            if (!params.getPassword().equals(params.getPasswordTry())) {
                return errorMessage(MessageCode.code_444, "两次输入的密码不一致！");
            }

            if (!(params.getPassword().length() >= 6 && params.getPassword().length() <= 20)) {
                return errorMessage(MessageCode.code_444, "请输入6-20位密码");
            }

            User userByMobile = userDao.getUserByMobile(params.getMobile());
            if (null != userByMobile) return errorMessage(MessageCode.code_444, "该手机号码已经注册！");

            final User inviteUser = userDao.getUserByCode(params.getInviteCode());
            if (null == inviteUser) return errorMessage(MessageCode.code_444, "推荐码错误，不存在！");

            User user = new User();
            user.setMobile(params.getMobile());
            user.setPassword(params.getPassword());
            user.setInviteUserId(inviteUser.getId());
            user.setTeamUserId(inviteUser.getInviteUserId());

            String code = user.getCode();
            User codeUser = userDao.getUserByCode(code);
            while (null != codeUser) {
                code = StringUtils.randomUpperString(6);
                codeUser = userDao.getUserByCode(code);
            }
            user.setCode(code);

            userDao.saveOrUpdate(user);
            globalService.clearRedisUserStored(user.getId());
            //globalService.addNewUser();

            return successMessage(new UserModel(user, 1, globalVariablesService.getGlobalRule().getDefaultAvatar()));
        }, null);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
